<template>
  <!--预览资源组件-->
  <div id="PreviewContainer" class="PreviewContainer" oncontextmenu="return false;">
    <div class="leftSourceList">
      <div class="leftMenu">
        <div class="logo"></div>
        <div class="menulist">
          <div class="lesson_btn sourceBtn" @click="getSource(1)">
            <div class="lesson_icon"></div>
            <span>课节资源</span>
          </div>
          <div class="teach_btn sourceBtn" @click="getSource(2)">
            <div class="teach_icon"></div>
            <span>教参资源</span>
          </div>
        </div>
      </div>
      <div class="leftsourcelist">
        <div class="top_title">
          <span v-if="sourceIndex==1">课节资料</span>
          <span v-else-if="sourceIndex==2">教参资料</span>
        </div>
        <div class="data_list">
          <table style="width:100%;" border="0" cellpadding="1" cellspacing="0">
            <tr
              v-if="sourceIndex==1"
              @click="play(li,$event)"
              :class="li.active"
              v-for="li in lessonSource"
            >
              <td style="width:1rem;">
                <div class="file-icon"></div>
              </td>
              <td style="max-width:2.2rem;">
                <div class="li-tr">
                  <div :title="li.lessonname" class="contentEllipsis lesson-name">{{li.lessonname}}</div>
                  <div
                    :title="li.sourcename"
                    style
                    class="contentEllipsis source-name"
                  >{{li.sourcename}}</div>
                </div>
              </td>
            </tr>
            <tr
              v-if="sourceIndex==2"
              @click="play(li,$event)"
              :class="li.active"
              v-for="li in teachSource"
            >
              <td style="width:1rem;">
                <div class="file-icon"></div>
              </td>
              <td style="max-width:2.2rem;">
                <div class="li-tr">
                  <div
                    :title="li.sourcename"
                    style="0.5rem;line-height: 0.5rem;"
                    class="contentEllipsis"
                  >{{li.sourcename}}</div>
                </div>
              </td>
            </tr>
          </table>
        </div>
      </div>
    </div>
    <div class="rightContent" v-if="initload">
      <div class="topbar"></div>
      <div class="sourceBox">
        <div class="source-name">
          <div class="lesson">
            {{curSource.lessonName}}
            <span v-if="islimited" style="color:#3887fe;">(正在备课中)</span>
          </div>
          <div class="source">{{curSource.sourceName}}</div>
        </div>
        <!-- <div v-if="islimited" class="source-name" style="margin-bottom: -0.9rem;">
          <div class="lesson" style="text-align:center;">正在备课中......</div>
        </div>-->
        <div id="source-package" class="source-package" :style="islimited?'padding: 1rem;':''">
          <!--mp3、mp4-->
          <div id="videoContainer" class="videoContainer" v-if="sourceType==1||sourceType==2">
            <videoPlayer
              class="video-player vjs-custom-skin videostyle"
              ref="videoPlayer"
              :playsinline="true"
              :options="playerOptions"
            ></videoPlayer>
          </div>
          <!--图片-->
          <div id="picContainer" class="picContainer" v-else-if="sourceType==3">
            <img class="imgnormal" :src="picOption.url" />
          </div>
          <!--pdf-->
          <div class="htmlContainer" v-else-if="sourceType==4">
            <pdf style="display: inline-block; width: 100%"
             :src="pdfData.pdfsrc"
             v-for="i in pdfData.pageCount"
             :key="i"
             :page="i">
            </pdf>
          </div>
          <!--html-->
          <div class="htmlContainer" v-else-if="sourceType==5">
            <iframe
              style="height:100%;width:100%;border: none;"
              allowfullscreen="true"
              :src="htmldata.html"
            ></iframe>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
let vm;
import { videoPlayer } from "vue-video-player";
import pdf from "vue-pdf";
import "video.js/dist/video-js.css";
export default {
  components: { videoPlayer, pdf },
  data() {
    return {
      initload: false,
      screenheight: 0, //屏幕高度
      leftSourceList: null, //左菜单对象
      timespan: 1600, //1600s后重取一次地址
      sourceIndex: 1, //1:课节资源 2:教参资源
      sourceType: 0, //1 视频MP4 2.音频MP3 3.图片 4.pdf 5.html
      lessonSource: [], //课节资源
      teachSource: [], //教参资源
      curSource: {
        lessonName: "", //环节名称
        sourceName: "", //资源名称
        lessonindex: 0, //课节资源当前选中
        sourceindex: 0 //教参资源当前选中
      },
      playerOptions: {
        //视频音频配置
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        controls: true, //控制条：boolean
        language: "zh-CN",
        aspectRatio: "10:5", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [],
        poster: "", //你的封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          PlayToggle: false,
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: false //全屏按钮
        }
      },
      picOption: {
        //图片配置
        url: ""
      },
      pdfData: {
        //pdf配置
        currentPage: 1,
        tempPage: 0, //临时当前页
        pageCount: 0,
        pdfsrc: ""
      },
      htmldata: {
        //html配置
        loading: false,
        html: ""
      },
      /**是否显示限制上课的样式 */
      islimited: true
    };
  },

  methods: {
    /**
     * 初始化
     */
    init() {
      let id = vm.$route.query.classSyllabusId;
      let index = vm.$route.query.index;
      let islimited = vm.$route.query.islimited;
      vm.loadPageData(id, index);
      vm.initload = true;
      vm.islimited = islimited == 1?true:false;
      //				$(document).keydown(function(e){
      //					if(e.key=="F12")return false;
      //				})
    },
    /**获取资源
     *
     **/
    getSource(param) {
      let $tab = $(".sourceBtn");

      if (param == 1) {
        //课节资源
        let tab = $tab.eq(0);
        tab
          .addClass("btnactive")
          .siblings()
          .removeClass("btnactive");
        vm.sourceIndex = 1;
        vm.$nextTick(function() {
          //dom更新完毕回调
          let event = $("table")
            .find("tr")
            .eq(vm.curSource.lessonindex)[0];
          if (vm.lessonSource.length > 0) {
            vm.play(vm.lessonSource[vm.curSource.lessonindex], event);
          }
        });
      } else if (param == 2) {
        //教参资源

        let tab = $tab.eq(1);
        tab
          .addClass("btnactive")
          .siblings()
          .removeClass("btnactive");
        vm.sourceIndex = 2;
        vm.$nextTick(function() {
          //dom更新完毕回调
          let event = $("table")
            .find("tr")
            .eq(vm.curSource.sourceindex)[0];
          if (vm.teachSource.length > 0) {
            vm.play(vm.teachSource[vm.curSource.sourceindex], event);
          }
        });
      }
    },

    /**
     * 播放预览资源 type:1 视频MP4 2.音频MP3 3.图片 4.pdf 5.html
     */
    play(li, event) {
      vm.initload = false;
      let e = event.currentTarget || event;
      $(e)
        .find(".li-tr")
        .addClass("li-tr-active");
      $(e)
        .siblings()
        .find(".li-tr")
        .removeClass("li-tr-active");
      $(e)
        .find(".li-tr .contentEllipsis")
        .addClass("active");
      $(e)
        .siblings()
        .find(".li-tr .contentEllipsis")
        .removeClass("active");
      // console.log(li);
      if (li.talkcloudFileId != null) {
        vm.$message({
          message: "在线课程资源暂不能预览！",
          type: "warning"
        });
        return;
      }
      let index = $(e).index();
      vm.playerOptions.sources = [];
      vm.sourceType = li.type;
      if (vm.sourceIndex == 1) {
        //课节资源
        vm.curSource.lessonindex = index;
      } else if (vm.sourceIndex == 2) {
        //教参资源
        vm.curSource.sourceindex = index;
      }
      if (li.accessUrl) {
        //再次加载文件

        let curTime = new Date().getTime();
        let time = (curTime - li.curTime) / 1000;
        if (time <= vm.timespan) {
          vm.load(li.type, li);
        } else {
          //文件地址过期重新获取
          vm.getFileurl(li);
        }
      } else {
        //初次加载文件
        vm.getFileurl(li);
      }
    },
    /**
     * 加载文件
     */
    load(index, li) {
      vm.initload = true;
      vm.curSource.lessonName = li.lessonname || "";
      vm.curSource.sourceName = li.sourcename || "";
      switch (index) {
        case 1: {
          //mp4
          //vm.playerOptions.poster = "";
          let newurl = tool.decrypt(li.accessUrl);
          vm.playerOptions.sources.push({ type: "video/mp4", src: newurl });
          vm.playerOptions.autoplay = true;
          vm.$nextTick(function() {
            //dom更新完毕回调
            let video = $(".videostyle .video-js .vjs-tech");
            video.removeClass("bgactive");
          });
          break;
        }
        case 2: {
          //MP3
          let newurl = tool.decrypt(li.accessUrl);
          vm.playerOptions.sources.push({ type: "audio/mp3", src: newurl });
          vm.playerOptions.autoplay = true;
          vm.$nextTick(function() {
            //dom更新完毕回调
            let video = $(".videostyle .video-js .vjs-tech");
            video.addClass("bgactive");
          });

          break;
        }
        case 3: {
          //图片
          //tool.test();

          let newurl = tool.decrypt(li.accessUrl);

          vm.picOption.url = newurl;

          break;
        }
        case 4: {
          //pdf
          let newurl = tool.decrypt(li.accessUrl);
          // vm.loadpdf(newurl);
          //vm.loadpdf('../../../static/'+li.sourcename);
          var loadingTask = pdf.createLoadingTask(newurl);
          loadingTask.then(pdf => {
              vm.pdfData.pageCount = pdf.numPages;
          });
          vm.pdfData.pdfsrc=loadingTask;
          break;
        }
        case 5: {
          //html
          let newurl = tool.decrypt(li.accessUrl);
          //   let param = {
          //     accept: "text/html, text/plain"
          //   };
          //  axios.get(newurl, param)
          //     .then(response => {
          //       // 处理HTML显示
          //       vm.htmldata.html = response.data;
          //     });
          vm.htmldata.html = newurl;
        }
      }
    },

    /**
     * 禁止右键菜单
     */
    doNothing() {
      window.event.returnValue = false;

      return false;
    },

    /**
     * 加载新数据
     */
    loadPageData(id, index) {
      //传参有变化则调用

      let param = { libraryCourseSyllabusId: id };
      vm.getSource(index);
      api.getLinkResourcesOfSyllabus(param).then(function(data) {
        let datafile = data.list;
        for (let i = 0; i < datafile.length; i++) {
          let type = datafile[i].lessonFileType;
          let resourceList = datafile[i].resourceList;
          if (type == 1) {
            //课节文件
            vm.lessonfile(resourceList, index);
          } else if (type == 2) {
            //教参文件
            vm.teachfile(resourceList, index);
          }
        }
      });
    },
    /**
     * 处理课节文件
     */
    lessonfile(data, index) {
      vm.lessonSource = [];
      for (let i = 0; i < data.length; i++) {
        let resourceName = data[i].resourceName;
        let index = resourceName.lastIndexOf(".");
        let suffix = resourceName.substring(index, resourceName.length);
        let filetype = vm.getFileType(suffix);
        let linkname = data[i].resourceAlias;
        let resourceId = data[i].resourceId;
        vm.lessonSource.push({
          lessonname: linkname,
          sourcename: resourceName,
          type: filetype,
          resourceId: resourceId,
          talkcloudFileId: data[i].talkcloudFileId
        });
      }
      let li = vm.lessonSource[0];
      if (index == 1) {
        //默认打开文件
        //vm.getFileurl(li);
        vm.$nextTick(function() {
          //dom更新完毕回调
          vm.curSource.lessonindex = 0;
          let event = $("table")
            .find("tr")
            .eq(vm.curSource.lessonindex)[0];
          vm.play(li, event);
        });
      }
    },
    /**
     * 处理教参文件
     */
    teachfile(data, index) {
      vm.teachSource = [];
      for (let i = 0; i < data.length; i++) {
        let resourceName = data[i].resourceName;
        let index = resourceName.lastIndexOf(".");
        let suffix = resourceName.substring(index, resourceName.length);
        let filetype = vm.getFileType(suffix);
        let resourceId = data[i].resourceId;
        vm.teachSource.push({
          sourcename: resourceName,
          type: filetype,
          resourceId: resourceId,
          talkcloudFileId: data[i].talkcloudFileId
        });
      }
      let li = vm.teachSource[0];
      if (index == 2) {
        //默认打开文件
        //vm.getFileurl(li);
        vm.$nextTick(function() {
          //dom更新完毕回调
          vm.curSource.sourceindex = 0;
          let event = $("table")
            .find("tr")
            .eq(vm.curSource.sourceindex)[0];
          vm.play(li, event);
        });
      }
    },
    /**
     * 获取文件类型码
     */
    getFileType(suffix) {
      let type = 0;
      switch (suffix) {
        case ".jpg": {
          type = 3;
          break;
        }
        case ".png": {
          type = 3;
          break;
        }
        case ".html": {
          type = 5;
          break;
        }
        case ".mp3": {
          type = 2;
          break;
        }
        case ".mp4": {
          type = 1;
          break;
        }
        case ".pdf": {
          type = 4;
          break;
        }
        default: {
          type = 5;
          break;
        }
      }

      return type;
    },
    /**
     * 取文件有效地址
     */
    getFileurl(li) {
      let index = li.type;
      vm.sourceType = li.type;
      let curTime = new Date().getTime();
      li.curTime = curTime;

      api
        .getResourceAccessUrl({ resourceId: li.resourceId })
        .then(function(data) {
          if (data.resultCode == 5000) {
            vm.$message({
              message: data.message,
              type: "warning"
            });
            return;
          } else {
            li.accessUrl = data.info.accessUrl;
            vm.load(index, li);
          }
        });
    },
    /**
     * 全屏
     */
    fullscreen() {
      // if (this.islimited) return;
      // let type = vm.sourceType;
      // let ele = document.getElementById("source-package");
      // if (type == 3) {
      //   tool.fullScreen(ele);
      // } else if (type == 5) {
      //   // console.log(ele);
      //   tool.fullScreen(ele);
      //   // window.open(vm.htmldata.html,"_blank");
      //   // window.location.href=vm.htmldata.html;
      // } else {
      //   tool.fullScreen(ele);
      // }
    },
    /**
     * 监听退出全屏
     */
    checkFull() {
      var isFull = document.webkitIsFullScreen || document.isFullScreen;
      //to fix : false || undefined == undefined
      if (isFull === undefined) {
        isFull = false;
      }
      return isFull;
    }
  },
  computed: {
    player() {
      return this.$refs.videoPlayer.player;
    }
  },
  mounted() {
    vm = this;
    vm.init();
    vm.screenheight = $(window).height();
    window.onresize = function() {
      let w = $(window).height();
      if (vm.leftSourceList == null) {
        vm.leftSourceList = $(".leftSourceList");
      }

      if (w < vm.screenheight) {
        vm.leftSourceList.css("height", vm.screenheight + "px");
      } else {
        vm.leftSourceList.css("height", "");
      }

      // if (!vm.checkFull()) {
      //   //退出全屏
      //   //要执行的动作
      //   if (vm.sourceType == 3) {
      //     $("#source-package").css("background", "#F3F6FD");
      //     $("#picContainer img")
      //       .removeClass("zoomout zoom imgzoom")
      //       .addClass("imgnormal");
      //     $("#picContainer img").off("click");
      //   }
      // } else {
      //   //进入全屏
      //   if (vm.sourceType == 3) {
      //     $("#source-package").css("background", "#0e0e0e");
      //     $("#picContainer img")
      //       .addClass("zoom")
      //       .removeClass("zoomout");
      //     $("#picContainer img").click(function() {
      //       let isexist = $(this).hasClass("imgnormal");
      //       if (isexist) {
      //         //正常图片
      //         $(this)
      //           .addClass("zoomout")
      //           .removeClass("zoom");
      //         $(this)
      //           .addClass("imgzoom")
      //           .removeClass("imgnormal");
      //       } else {
      //         //放大图片
      //         $(this)
      //           .addClass("zoom")
      //           .removeClass("zoomout");
      //         $(this)
      //           .addClass("imgnormal")
      //           .removeClass("imgzoom");
      //       }
      //     });
      //   }
      // }
    };
  },
  watch: {
    // 利用watch方法检测路由变化：
    $route: function(to, from) {
      // 拿到目标参数 to.query.classSyllabusId 去再次请求数据接口
      vm.loadPageData(to.query.classSyllabusId, to.query.index);
    }
  },
  created : function() {
  	var isExist = tool.checkFont("FZKai-Z03S");
  	//字体不存在
  	if(!isExist) {
  		this.$confirm('当前环境缺少课件播放必须的字体，是否下载?', '字体下载提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          window.open("https://bj.bcebos.com/v1/alphakids/vxiao/tools/方正楷体简.TTF","_self");
        	tool.notify({
	          title: '字体安装提示',
	          message: '1. 下载字体文件到本地\n2. 双击打开字体文件\n3. 点击安装按钮执行安装操作\n4. 重启浏览器，字体生效',
	          duration: 0
	        });
        }).catch(() => {});
  	}
  }
};
</script>

<style lang="scss">
.PreviewContainer {
  width: 19.2rem;
  height: 100%;
  display: flex;
  overflow: auto;

  /**文字超出样式**/
  .contentEllipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .leftSourceList {
    width: 4rem;
    height: 100%;
    display: inline-flex;
    .leftMenu {
      width: 0.8rem;
      height: 100%;
      position: relative;
      .logo {
        width: 0.8rem;
        height: 0.8rem;
        background: #3887fe;
        border-bottom: 1px solid rgba(236, 236, 237, 0.5);
        background-image: url(../../assets/img/common/logo.png);
        background-size: 0.7rem 0.6rem;
        background-position: 0.05rem 0.1rem;
        background-repeat: no-repeat;
      }
      .menulist {
        width: 0.8rem;
        height: calc(100% - 0.81rem);
        background: #3887fe;
        .lesson_btn {
          width: 0.8rem;
          height: 0.8rem;
          top: 0.5rem;
          position: relative;
          cursor: pointer;
          color: #ffffff;
          text-align: center;
          line-height: 1.2rem;
          font-size: 0.16rem;
          .lesson_icon {
            width: 0.38rem;
            height: 0.33rem;
            background-image: url(../../assets/img/common/lessonicon.png);
            background-size: 0.38rem 0.33rem;
            background-repeat: no-repeat;
            position: absolute;
            left: 50%;
            margin-left: -0.19rem;
            top: 50%;
            margin-top: -0.25rem;
          }
        }
        .teach_btn {
          width: 0.8rem;
          height: 0.8rem;
          top: 1rem;
          position: relative;
          cursor: pointer;
          color: #ffffff;
          text-align: center;
          line-height: 1.2rem;
          font-size: 0.16rem;
          .teach_icon {
            width: 0.38rem;
            height: 0.33rem;
            background-image: url(../../assets/img/common/teachicon.png);
            background-size: 0.38rem 0.33rem;
            background-repeat: no-repeat;
            position: absolute;
            left: 50%;
            margin-left: -0.19rem;
            top: 50%;
            margin-top: -0.26rem;
          }
        }
        .btnactive {
          background: rgba(0, 0, 0, 0.2);
          opacity: 0.8;
        }
      }
    }
    .leftsourcelist {
      width: calc(100% - 0.8rem);
      height: 100%;
      position: relative;
      .top_title {
        width: 100%;
        height: 0.8rem;
        border-bottom: 1px solid rgba(236, 236, 237, 0.5);
        border-right: 1px solid rgba(236, 236, 237, 0.5);
        line-height: 0.8rem;
        text-indent: 0.3rem;
        font-weight: bold;
        font-size: 0.2rem;
        background: #fbfcfd;
      }
      .data_list {
        width: 100%;
        height: calc(100% - 0.81rem);
        border-right: 1px solid rgba(236, 236, 237, 0.5);
        overflow: auto;
        &::-webkit-scrollbar {
          width: 0.03rem;
          height: 0;
        }
        &::-webkit-scrollbar-thumb {
          border-radius: 0.03rem;
          background: #3885f8;
        }
        .file-icon {
          width: 1rem;
          height: 0.8rem;
          background-image: url(../../assets/img/common/fileicon.png);
          background-size: 0.44rem 0.34rem;
          background-position: 0.28rem 0.23rem;
          background-repeat: no-repeat;
        }
        .activetr {
          color: #3887fe;
        }
        .li-tr {
          width: 98%;
          height: 0.5rem;
          line-height: 0.5rem;
          font-size: 0.16rem;
          color: #666666;
          .lesson-name {
            height: 0.25rem;
            line-height: 0.25rem;
            font-size: 0.18rem;
            font-weight: bold;
            color: #333333;
          }
          .source-name {
            height: 0.25rem;
            line-height: 0.25rem;
            font-size: 0.16rem;
            color: #666666;
          }
          .active {
            color: #3887fe;
          }
        }
        .li-tr-active {
          border-right: 0.04rem solid #3887fe;
        }
        table tr {
          font-size: 0.14rem;
          height: 0.8rem;
          cursor: pointer;
        }
        table tr td {
          border-bottom: 1px solid #f3f6fd;
        }
      }
    }
  }
  .rightContent {
    width: calc(100% - 4rem);
    height: 100%;
    background: rgba(0, 0, 0, 0);
    .topbar {
      width: 100%;
      height: 0.8rem;
      padding: 0.31rem 0.4rem;
      border-bottom: 1px solid rgba(236, 236, 237, 0.5);
      .closeBtn {
        height: 0.15rem;
        width: 0.15rem;
        float: right;
        cursor: pointer;
        background: url(../../assets/img/education_manage/close.png);
        background-size: 0.15rem 0.15rem;
      }
    }

    .sourceBox {
      width: 100%;
      height: calc(100% - 0.81rem);
      padding: 0rem 0.7rem;
      .source-name {
        width: 100%;
        height: 0.8rem;
        .lesson {
          width: 100%;
          height: 0.5rem;
          line-height: 0.7rem;
          font-size: 0.18rem;
          font-weight: bold;
          color: #141414;
        }
        .source {
          width: 100%;
          height: 0.3rem;
          line-height: 0.2rem;
          font-size: 0.16rem;
          color: #333333;
        }
      }
      .source-package {
        width: 100%;
        height: 7.6rem;
        overflow: auto;
        margin-top: 0.1rem;
        background: #f3f6fd;
        &::-webkit-scrollbar {
          width: 0.03rem;
          height: 0;
        }
        &::-webkit-scrollbar-thumb {
          border-radius: 0.01rem;
          background: #3887fe;
        }

        .videoContainer {
          width: 100%;
          height: 100%;
          display: flex;
          align-content: center;
          justify-content: center;
          .videostyle {
            width: 100%;
            height: 100%;
            align-self: center;
            .bgactive {
              background-size: 100% 100%;
              background: url(../../assets/img/common/mp3.png);
              background-position: center;
              background-repeat: no-repeat;
            }
          }
          .video-js .vjs-fullscreen-control {
            display: none;
          }
        }

        .picContainer {
          width: 100%;
          height: 100%;
          display: flex;
          align-content: center;
          justify-content: center;
          .imgnormal {
            width: auto;
            height: 7rem;
            align-self: center;
          }
          .imgzoom {
            width: 90%;
            height: auto;
            align-self: flex-start;
          }
          .zoom {
            cursor: url("../../assets/img/common/zoomicon.png"), auto;
          }
          .zoomout {
            cursor: url("../../assets/img/common/zoomouticon.png"), auto;
          }
        }
        .htmlContainer {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>